package com.ez2find.backing;

import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.model.RegisterUser;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class UsersBean {

    @EJB
    RegisterUserManagerLocal ejbUsers;
    private RegisterUser user;
    private int indexUsers;
    private boolean newUser;
    private String pass1;
    private String pass2;
    private boolean linkRPOk;

    public UsersBean() {
    }

    public String saveUser() {
        System.out.println("Saving changes..");
        try {
            if ((user.getEmail().length() < 4) || !user.getEmail().contains("@") || !user.getEmail().contains(".")) {
                FacesMessage msg = new FacesMessage("Please enter a valid email.");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }

            if ((getUser() != null) && (getUser().getId() != null)) {
                if ((pass1 != null && !pass1.equals("")) || (pass2 != null && !pass2.equals(""))) {
                    if (!pass1.equals(pass2)) {
                        FacesMessage msg = new FacesMessage("The news passwords don't equals");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    user.setPassword(pass1);
                    ejbUsers.update(user, true);
                    System.out.println("User updated correctly.");
                    FacesMessage msg = new FacesMessage("User updated correctly.");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    newUser = false;
                    user = null;
                    linkRPOk = false;
                    return null;
                } else {
                    ejbUsers.update(user, false);
                    System.out.println("User updated correctly.");
                    FacesMessage msg = new FacesMessage("User updated correctly.");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    newUser = false;
                    user = null;
                    linkRPOk = false;
                    return null;
                }
            } else {
                if (pass1 == null || pass1.equals("") || pass2 == null || pass2.equals("")) {
                    FacesMessage msg = new FacesMessage("The passwords is required");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                if (!pass1.equals(pass2)) {
                    FacesMessage msg = new FacesMessage("The passwords don't equals");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return null;
                }
                RegisterUser userAccount = ejbUsers.findUserByEmail(user.getEmail());
                if (userAccount != null) {
                    if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                        FacesMessage msg = new FacesMessage("The User Account exist.");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        FacesMessage msg1 = new FacesMessage("If you forgot your password or need to reactive your account click in the link to recovery password.");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg1);
                        setLinkRPOk(true);
                        return null;
                    }
                    userAccount.setPassword(pass1);
                    userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                    Random r = new Random();
                    String token = Long.toString(Math.abs(r.nextLong()), 36);
                    userAccount.setConfirmationCode(token);
                    ejbUsers.update(userAccount, true);
                    indexUsers = (int) (userAccount.getId() - 1 / 100 + 1);
                    System.out.println("User created correctly.");
                    FacesMessage msg = new FacesMessage("User created correctly.");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    newUser = false;
                    user = null;
                    linkRPOk = false;
                    return null;
                }
                user.setPassword(pass1);
                user.setNumberOfPostings(50);
                user.setRegisterDate(new Date(System.currentTimeMillis()));
                Random r = new Random();
                String token = Long.toString(Math.abs(r.nextLong()), 36);
                user.setConfirmationCode(token);
                ejbUsers.createUser(user);
                indexUsers = ejbUsers.listAll().size() - 1 / 100 + 1;
                System.out.println("User created correctly.");
                FacesMessage msg = new FacesMessage("User created correctly.");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                newUser = false;
                user = null;
                linkRPOk = false;
                return null;
            }

        } catch (Exception ex) {
            FacesMessage msg = new FacesMessage("Error creating/updating user.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            Logger.getLogger(UsersBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public String removeUser() {
        try {
            //SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
            ejbUsers.delete(user);
            newUser = false;
            user = null;
            linkRPOk = false;
            System.out.println("User removed");
            FacesMessage msg = new FacesMessage("User removed.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        } catch (Exception ex) {
            newUser = false;
            user = null;
            linkRPOk = false;
            FacesMessage msg = new FacesMessage("User can not removed.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
        return null;
    }

    public List<RegisterUser> getUsers() {
        return ejbUsers.listAll();
    }

    public String checkingUsers() {
        try {
            for (RegisterUser u : ejbUsers.listAll()) {
                if (u.getStatus().equals("pending")) {
                    if ((u.getRegisterDate().getTime() + 604800000) < System.currentTimeMillis()) {
                        ejbUsers.delete(u);
                    }
                } else {
                    if (u.getStatus().equals("active")) {
                        if (u.getLoggedDate() != null) {
                            if ((u.getLoggedDate().getTime() + 7776000000L) < System.currentTimeMillis()) {
                                ejbUsers.delete(u);
                            }
                        } else if ((u.getRegisterDate().getTime() + 7776000000L) < System.currentTimeMillis()) {
                            ejbUsers.delete(u);
                        }
                    } else {
                        if(u.getLoggedDate() != null){
                            if ((u.getPosts() == null || u.getPosts().isEmpty()) && (u.getLoggedDate().getTime() + 604800000) < System.currentTimeMillis()) {
                                ejbUsers.delete(u);
                            }
                        } else if ((u.getPosts() == null || u.getPosts().isEmpty()) && (u.getRegisterDate().getTime() + 604800000) < System.currentTimeMillis()) {
                                ejbUsers.delete(u);
                            }
                    }
                }
            }
            FacesMessage msg = new FacesMessage("Users checking succesfully completed");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Error checking Users");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

// <editor-fold defaultstate="collapsed" desc="Setters and getters"> 
    public RegisterUser getUser() {
        if (user == null) {
            user = new RegisterUser();
        }
        return user;
    }

    public void setUser(RegisterUser user) {
        this.user = user;
    }

    public boolean isNewUser() {
        return newUser;
    }

    public void setNewUser(boolean newUser) {
        this.newUser = newUser;
    }

    public String getPass2() {
        return pass2;
    }

    public void setPass2(String pass2) {
        this.pass2 = pass2;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String getPass1() {
        return pass1;
    }

    public void setPass1(String pass1) {
        this.pass1 = pass1;
    }

    public int getIndexUsers() {
        return indexUsers;
    }

    public void setIndexUsers(int indexUsers) {
        this.indexUsers = indexUsers;
    }
// </editor-fold>
}
